import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {env} from "@env/environment";

/*
  Generated class for the NativeUploadProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NativeUploadProvider {

  constructor(private http: HttpClient) {
  }

  upload(base64: string): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      let blob = this.dataURLtoBlob(base64);
      let formData: FormData = new FormData();
      formData.append('file', blob, (new Date().getTime() + ".jpg"));
      this.http.post(env.app_serve_url + "/FormUpload/multiUpload.do", formData).subscribe((message) => {
        let fileList = message["data"]["resultData"];
        resolve(fileList[0]);
      }, error => {
        reject(error);
      });
    })
  }

  dataURLtoBlob(base64: string) {
    let arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type: mime});
  }
}
